from rest_framework import serializers
from .models import HostMetrics, ProcessInfo, ServiceStatus, AlertRule
from cmdb.models import Host


class HostMetricsSerializer(serializers.ModelSerializer):
    """主机监控指标序列化器"""
    hostname = serializers.CharField(source='host.hostname', read_only=True)
    host_ip = serializers.CharField(source='host.ip', read_only=True)

    class Meta:
        model = HostMetrics
        fields = '__all__'

    def to_representation(self, instance):
        """自定义序列化输出"""
        data = super().to_representation(instance)
        
        # 添加计算字段
        data['memory_usage_gb'] = instance.memory_usage_gb
        data['disk_usage_gb'] = instance.disk_usage_gb
        
        # 格式化百分比
        data['cpu_usage_formatted'] = f"{instance.cpu_usage:.1f}%"
        data['memory_usage_formatted'] = f"{instance.memory_usage:.1f}%"
        data['disk_usage_formatted'] = f"{instance.disk_usage:.1f}%"
        
        return data


class ProcessInfoSerializer(serializers.ModelSerializer):
    """进程信息序列化器"""
    hostname = serializers.CharField(source='host.hostname', read_only=True)

    class Meta:
        model = ProcessInfo
        fields = '__all__'

    def to_representation(self, instance):
        """自定义序列化输出"""
        data = super().to_representation(instance)
        
        # 格式化内存大小
        data['memory_rss_mb'] = round(instance.memory_rss / (1024*1024), 2)
        data['memory_vms_mb'] = round(instance.memory_vms / (1024*1024), 2)
        
        return data


class ServiceStatusSerializer(serializers.ModelSerializer):
    """服务状态序列化器"""
    hostname = serializers.CharField(source='host.hostname', read_only=True)

    class Meta:
        model = ServiceStatus
        fields = '__all__'


class AlertRuleSerializer(serializers.ModelSerializer):
    """告警规则序列化器"""
    
    class Meta:
        model = AlertRule
        fields = '__all__'

    def validate(self, data):
        """验证告警规则"""
        metric_type = data.get('metric_type')
        threshold = data.get('threshold')
        operator = data.get('operator')
        
        # 验证百分比类型的阈值
        if metric_type in ['cpu_usage', 'memory_usage', 'disk_usage']:
            if threshold < 0 or threshold > 100:
                raise serializers.ValidationError("百分比类型的阈值必须在0-100之间")
        
        # 验证负载类型的阈值
        if metric_type == 'load_average':
            if threshold < 0:
                raise serializers.ValidationError("负载阈值不能为负数")
        
        return data


class HostMetricsStatsSerializer(serializers.Serializer):
    """主机监控统计序列化器"""
    host_id = serializers.IntegerField()
    time_range = serializers.ChoiceField(
        choices=['1h', '24h', '7d', '30d'],
        default='1h'
    )
    metrics = serializers.ListField(
        child=serializers.ChoiceField(choices=[
            'cpu_usage', 'memory_usage', 'disk_usage', 
            'load_average', 'network_io'
        ]),
        default=['cpu_usage', 'memory_usage', 'disk_usage']
    )

    def validate_host_id(self, value):
        """验证主机ID"""
        try:
            Host.objects.get(id=value, is_active=True)
        except Host.DoesNotExist:
            raise serializers.ValidationError("主机不存在或已禁用")
        return value


class HostMetricsRealTimeSerializer(serializers.ModelSerializer):
    """实时监控数据序列化器"""
    hostname = serializers.CharField(source='host.hostname', read_only=True)
    host_ip = serializers.CharField(source='host.ip', read_only=True)

    class Meta:
        model = HostMetrics
        fields = [
            'id', 'host', 'hostname', 'host_ip',
            'cpu_usage', 'memory_usage', 'disk_usage',
            'cpu_load_1m', 'cpu_load_5m', 'cpu_load_15m',
            'process_count', 'zombie_process_count',
            'network_bytes_sent', 'network_bytes_recv',
            'collected_at'
        ]

    def to_representation(self, instance):
        """自定义序列化输出"""
        data = super().to_representation(instance)
        
        # 添加状态判断
        data['status'] = 'normal'
        if instance.cpu_usage > 80 or instance.memory_usage > 80 or instance.disk_usage > 90:
            data['status'] = 'warning'
        if instance.cpu_usage > 95 or instance.memory_usage > 95 or instance.disk_usage > 95:
            data['status'] = 'critical'
        
        # 添加网络IO速率（简化计算）
        data['network_io'] = {
            'bytes_sent': instance.network_bytes_sent,
            'bytes_recv': instance.network_bytes_recv,
            'packets_sent': instance.network_packets_sent,
            'packets_recv': instance.network_packets_recv
        }
        
        return data


class TopProcessesSerializer(serializers.Serializer):
    """TOP进程序列化器"""
    host_id = serializers.IntegerField()
    limit = serializers.IntegerField(default=10, min_value=1, max_value=50)
    sort_by = serializers.ChoiceField(
        choices=['cpu_percent', 'memory_percent'],
        default='cpu_percent'
    )

    def validate_host_id(self, value):
        """验证主机ID"""
        try:
            Host.objects.get(id=value, is_active=True)
        except Host.DoesNotExist:
            raise serializers.ValidationError("主机不存在或已禁用")
        return value


class HostStatusSummarySerializer(serializers.Serializer):
    """主机状态汇总序列化器"""
    total_hosts = serializers.IntegerField()
    online_hosts = serializers.IntegerField()
    offline_hosts = serializers.IntegerField()
    warning_hosts = serializers.IntegerField()
    critical_hosts = serializers.IntegerField()
    
    def to_representation(self, instance):
        """自定义序列化输出"""
        data = super().to_representation(instance)
        
        # 添加百分比
        total = data['total_hosts']
        if total > 0:
            data['online_percentage'] = round(data['online_hosts'] / total * 100, 1)
            data['offline_percentage'] = round(data['offline_hosts'] / total * 100, 1)
            data['warning_percentage'] = round(data['warning_hosts'] / total * 100, 1)
            data['critical_percentage'] = round(data['critical_hosts'] / total * 100, 1)
        else:
            data['online_percentage'] = 0
            data['offline_percentage'] = 0
            data['warning_percentage'] = 0
            data['critical_percentage'] = 0
        
        return data


class MonitoringTaskStatusSerializer(serializers.Serializer):
    """监控任务状态序列化器"""
    task_name = serializers.CharField()
    status = serializers.CharField()
    last_run = serializers.DateTimeField()
    next_run = serializers.DateTimeField()
    success_count = serializers.IntegerField()
    failure_count = serializers.IntegerField()
    average_duration = serializers.FloatField()


class AlertSerializer(serializers.Serializer):
    """告警序列化器"""
    id = serializers.IntegerField()
    host_id = serializers.IntegerField()
    hostname = serializers.CharField()
    metric_type = serializers.CharField()
    current_value = serializers.FloatField()
    threshold = serializers.FloatField()
    severity = serializers.CharField()
    message = serializers.CharField()
    triggered_at = serializers.DateTimeField()
    is_resolved = serializers.BooleanField()
    resolved_at = serializers.DateTimeField(allow_null=True)


class MetricsExportSerializer(serializers.Serializer):
    """监控数据导出序列化器"""
    host_ids = serializers.ListField(child=serializers.IntegerField(), required=False)
    start_time = serializers.DateTimeField()
    end_time = serializers.DateTimeField()
    metrics = serializers.ListField(
        child=serializers.ChoiceField(choices=[
            'cpu_usage', 'memory_usage', 'disk_usage',
            'load_average', 'network_io', 'process_info'
        ])
    )
    format = serializers.ChoiceField(choices=['csv', 'json', 'excel'], default='csv')

    def validate(self, data):
        """验证导出参数"""
        start_time = data.get('start_time')
        end_time = data.get('end_time')
        
        if start_time >= end_time:
            raise serializers.ValidationError("开始时间必须早于结束时间")
        
        # 限制导出时间范围（最多30天）
        if (end_time - start_time).days > 30:
            raise serializers.ValidationError("导出时间范围不能超过30天")
        
        return data
